package com.qf.sms.service.impl;


import com.qf.sms.dao.SmsHisDao;
import com.qf.sms.model.SmsHis;
import com.qf.sms.model.SmsHisExample;
import com.qf.sms.service.SmsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 3090
 */

@Service
public class SmsServiceImpl implements SmsService {

    public static final int MAX_SMS_TIME = 1000 * 60 * 5;
    @Resource
    private SmsHisDao smsHisDao;

    @Override
    public int saveSms(String phoneNo, String code, Integer serviceId) {
        SmsHis smsHis = new SmsHis();
        smsHis.setPhoneNo(phoneNo);
        smsHis.setCode(code);
        smsHis.setServiceId(serviceId);
        int result = smsHisDao.insertSelective(smsHis);
        return result;
    }


    @Override
    public int checkSms(String phoneNo, String code, Integer serviceId) {
        //查询数据
        SmsHisExample example = new SmsHisExample();
        SmsHisExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneNoEqualTo(phoneNo);
        criteria.andServiceIdEqualTo(serviceId);

        //设置排序
        example.setOrderByClause("`time` desc");
        List<SmsHis> smsHis = smsHisDao.selectByExample(example);
        if (smsHis != null && smsHis.size() > 0) {
            SmsHis sms = smsHis.get(0);
            if (sms.getCode().equals(code)) {
                //验证码相同
                if (System.currentTimeMillis() - sms.getTime().getTime() <= MAX_SMS_TIME) {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                smsHis.remove(0);
                for (int i = 0; i < smsHis.size(); i++) {
                    sms = smsHis.get(i);
                    if (sms.getCode().equals(code)) {
                        return 2;
                    }
                }
                return 3;
            }
        }
        return 3;
    }
}
